<template>
  <XnDialog
    custom-class="add-org-dialog"
    :title="type === 'edit' ? '编辑单位' : '添加单位'"
    :visible.sync="selfVisible"
    @close="closeDialog">
    <el-form ref="orgForm" :model="orgForm" :rules="rules" label-position="top" size="small">
      <div class="row-item">
        <div class="col-item">
          <el-form-item label="单位名称" prop="orgName">
            <el-input
              v-model.trim="orgForm.orgName"
              autocomplete="off"
              :maxlength="30"
              show-word-limit
              clearable
              placeholder="请输入"
              @clear="onAliasChange"></el-input>
          </el-form-item>
        </div>
        <div class="col-item">
          <el-form-item label="单位简称" prop="orgAlias">
            <el-input
              v-model.trim="orgForm.orgAlias"
              autocomplete="off"
              :maxlength="20"
              show-word-limit
              clearable
              placeholder="请输入"
              @change="onAliasChange"
              @blur="onAliasChange"
              @clear="onAliasChange"></el-input>
          </el-form-item>
        </div>
        <!-- <div class="col-item">
          <el-form-item label="上级单位" prop="pid">
            <el-cascader
              v-model="orgForm.pid"
              :options="orgTreeList"
              :props="{ emitPath: false, checkStrictly: true, value: 'id', label: 'orgName', children: 'queryOutVOS' }"
              clearable
              :disabled="noSelectPid"></el-cascader>
          </el-form-item>
        </div> -->
      </div>
      <div class="row-item">
        <div class="col-item">
          <el-form-item label="单位类型" prop="orgType">
            <el-select v-model="orgForm.orgType" placeholder="请选择单位类型" clearable>
              <el-option v-for="item in typeList" :label="item.name" :key="item.code" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div v-if="type !== 'edit'" class="col-item">
          <el-form-item label="账号" prop="loginName">
            <el-input
              v-model.trim="orgForm.loginName"
              autocomplete="off"
              :maxlength="16"
              show-word-limit
              clearable
              placeholder="请输入"></el-input>
          </el-form-item>
        </div>
      </div>
      <template v-if="type !== 'edit'">
        <div class="row-item">
          <div class="col-item">
            <el-form-item label="负责人" prop="accountName">
              <el-input v-model.trim="orgForm.accountName" autocomplete="off" clearable placeholder="请输入"></el-input>
            </el-form-item>
          </div>
          <div class="col-item">
            <el-form-item label="负责人职务" prop="postName">
              <el-input
                v-model.trim="orgForm.postName"
                autocomplete="off"
                :maxlength="50"
                show-word-limit
                clearable
                placeholder="请输入"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="row-item">
          <div class="col-item">
            <el-form-item label="负责人手机号" prop="telephone">
              <el-input
                v-model.trim="orgForm.telephone"
                name="phone"
                :maxlength="11"
                autocomplete="off"
                clearable
                placeholder="请输入"></el-input>
            </el-form-item>
          </div>
          <div class="col-item">
            <el-form-item label="密码" prop="password">
              <el-popover trigger="focus" placement="left" popper-class="password-tips-popover">
                <div class="password-tip-con">
                  <p class="tips-title">密码设置规则</p>
                  <p class="tips-con">1. 8~16位数字、字母和特殊符号的组合</p>
                  <p class="tips-con">2. 特殊字符包含：!@#$%^&*+=_.()&lt;&gt;?</p>
                </div>
                <el-input
                  v-model.trim="orgForm.password"
                  :type="inpType"
                  name="password"
                  autocomplete="new-password"
                  slot="reference"
                  label="密码"
                  placeholder="请输入密码"
                  style="width: 60%">
                  <span slot="suffix" class="pwd-eye-view" @click="togglePwdDisplay">
                    <i class="iconfont icon-biyan" v-show="inpType === 'password'"></i>
                    <i class="iconfont icon-zhengyan" v-show="inpType === 'text'"></i>
                  </span>
                </el-input>
              </el-popover>
              <el-button
                type="primary"
                size="small"
                :loading="loading"
                @click.stop="createPassword"
                style="margin-left: 12px">
                随机密码
              </el-button>
            </el-form-item>
          </div>
        </div>
      </template>

      <div class="btn-box">
        <el-button size="small" @click.stop="closeDialog">取消</el-button>
        <el-button size="small" type="primary" @click.stop="onFormSave">确定</el-button>
      </div>
    </el-form>
  </XnDialog>
</template>
<script>
import XnDialog from '@com/xnDialog.vue'
import { pwdReg2 } from '@utility/regExps.js'
import { randomPassword } from '@utility/utility.js'
import pinyin from 'js-pinyin'
export default {
  name: 'AddOrgDialog',
  components: { XnDialog },
  emits: ['close', 'submit'],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: 'add',
    },
    // 单位类型
    typeList: {
      type: Array,
      default: () => [],
    },
    // 组织单位
    orgList: {
      type: Array,
      default: () => [],
    },
    info: {
      type: Object,
      default: () => {},
    },
    // 上一级信息
    parentInfo: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    // const checkPhone = (rule, value, cb) => {
    //   if (!value) {
    //     cb(new Error('请输入负责人联系电话'))
    //   } else if (phoneReg.test(value)) {
    //     cb()
    //   } else {
    //     cb(new Error('请输入有效的手机号'))
    //   }
    // }
    const checkPwd = (rule, value, cb) => {
      if (!value) {
        cb(new Error('密码不能为空'))
      } else if (pwdReg2.test(value)) {
        cb()
      } else {
        cb(new Error('8~16位数字、字母和特殊符号的组合'))
      }
    }
    const checkAccount = (rule, value, cb) => {
      if (!value) {
        cb(new Error('账号不能为空'))
      } else if (/^[a-zA-Z][a-zA-Z0-9_]{7,15}$/.test(value)) {
        cb()
      } else {
        cb(new Error('8~16位以字母开头的字母和数字的组合'))
      }
    }
    return {
      selfVisible: false,
      orgForm: {
        id: '',
        orgType: '',
        pid: '',
        orgName: '',
        orgAlias: '',
        isSecrecy: false,
        postName: '',
        telephone: '',
        accountName: '',
        loginName: '',
        password: '',
      },
      rules: {
        orgType: [{ required: true, message: '请选择单位类型', trigger: 'change' }],
        orgName: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
        accountName: [{ required: true, message: '请输入负责人名字', trigger: 'blur' }],
        // telephone: [{ required: false, validator: checkPhone, trigger: 'blur' }],
        loginName: [{ required: true, validator: checkAccount, trigger: 'blur' }],
        password: [{ required: true, validator: checkPwd, trigger: 'blur' }],
      },
      orgTreeList: [],
      inpType: 'password',
      loading: false,
    }
  },
  watch: {
    visible(bool) {
      this.selfVisible = bool
    },
    info: {
      handler(obj) {
        if (obj && obj.id) {
          if (this.type === 'edit') {
            this.orgForm = {
              ...this.orgForm,
              ...obj,
              orgType: obj.orgTypeId,
            }
            this.orgTreeList = this.setTree(this.orgList, 0)
          } else {
            this.orgForm.pid = obj.id
          }

          // if (!obj.loginName && (obj.orgAlias || obj.orgName)) {
          //   this.orgForm.loginName = 'XNKH_' + pinyin.getCamelChars(obj.orgAlias || obj.orgName) + '001'
          // }
        }
      },
      deep: true,
      immediate: true,
    },
    orgList: {
      handler(list) {
        if (list && list.length) {
          this.orgTreeList = this.setTree(list, 0)
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // 禁止选择上级单位
    noSelectPid() {
      let bool = false
      if (this.type === 'addNext') {
        bool = true
      } else if (this.type === 'edit' && this.info.id === localStorage.orgId && this.info.pid === '-1') {
        bool = true
      }
      return bool
    },
  },
  created() {
    pinyin.setOptions({ checkPolyphone: false, charCase: 0 })
  },
  methods: {
    closeDialog() {
      this.$refs.orgForm && this.$refs.orgForm.resetFields()
      this.orgForm = {
        id: '',
        orgType: '',
        pid: '',
        orgName: '',
        orgAlias: '',
        isSecrecy: false,
        postName: '',
        telephone: '',
        accountName: '',
        loginName: '',
        password: '',
      }
      this.selfVisible = false
      this.$emit('close', false)
      this.$emit('update:visible', false)
    },
    onAliasChange() {
      if (this.type === 'edit' && this.info.id) {
        return false
      }
      if (!this.orgForm.orgAlias && !this.orgForm.orgName) {
        this.orgForm.loginName = ''
      } else {
        let accountName = this.orgForm.orgAlias || this.orgForm.orgName
        if (accountName.length > 8) {
          accountName = accountName.slice(0, 8)
        }
        this.orgForm.loginName = 'XNKH_' + pinyin.getCamelChars(accountName) + '001'
      }
    },

    // 输入框过滤
    onPhoneChange(e) {
      console.log(e, this.orgForm.telephone)
    },
    // 重置树结构的叶子结点
    setTree(datas, level, bool = false) {
      let lastInx = false
      for (let i = 0; i < datas.length; i++) {
        lastInx = i === datas.length - 1
        if (this.type === 'edit' && this.info.id === datas[i].id) {
          datas[i].disabled = true
        } else {
          datas[i].disabled = bool
        }
        if (datas[i].queryOutVOS && datas[i].queryOutVOS.length === 0) {
          delete datas[i].queryOutVOS
        }
        if (datas[i].queryOutVOS && datas[i].queryOutVOS.length) {
          this.setTree(datas[i].queryOutVOS, level + 1, datas[i].disabled)
        }
      }
      if (level === 0 && lastInx) {
        return datas
      }
    },
    togglePwdDisplay() {
      this.inpType = this.inpType === 'password' ? 'text' : 'password'
    },
    createPassword() {
      const passwordLength = 10
      this.orgForm.password = randomPassword(passwordLength)
      this.inpType = 'text'
      this.$refs.orgForm.validateField('password')
    },
    onFormSave() {
      this.$refs.orgForm.validate(valid => {
        if (valid) {
          this.$emit('submit', this.orgForm)
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.add-org-dialog {
  ::v-deep &.el-dialog {
    margin-top: 5vh !important;
    width: 640px;
    .el-form {
      .row-item {
        width: 100%;
        display: flex;
        align-items: center;
        .col-item {
          width: 50%;
          margin-right: 20px;
          position: relative;
          &:last-of-type {
            margin-right: 0px;
          }
        }
        .col-item.col-item1 {
          width: 100%;
          margin-right: 0;
        }
      }
      .el-cascader,
      .el-input,
      .el-select {
        width: 100%;
      }
      .pwd-eye-view {
        cursor: pointer;
      }
      .btn-box {
        text-align: right;
        margin-top: 20px;
        border-top: 1px solid #dedede;
        padding-top: 20px;
      }
    }
  }
}
</style>
<style lang="scss">
.el-popover {
  &.password-tips-popover {
    .password-tip-con {
      .tips-title {
        font-size: 15px;
        list-style: 24px;
        margin-bottom: 10px;
        color: #333;
      }

      .tips-con {
        font-size: 13px;
        list-style: 20px;
        margin-bottom: 5px;
        color: #666;
      }
    }
  }
}
.el-cascader-menu {
  .el-radio.is-disabled {
    color: #999;
    cursor: not-allowed;
  }
  .el-radio.is-disabled + .el-cascader-node__label {
    color: #999;
    cursor: not-allowed;
  }
}
</style>
